package clients

import (
	"errors"
	"fmt"

	"github.com/facebookgo/inject"
	"github.com/go-resty/resty/v2"
	jsoniter "github.com/json-iterator/go"
	"gitlab.yunzhen-data.com/C-Chain/titan/bytesutils"
	"gitlab.yunzhen-data.com/C-Chain/titan/injectutils"

	"gitlab.yunzhen-data.com/C-Chain/titan-template/configurations"
)

var ErrMissHTTPClientConfigurationInInjector = errors.New("miss http client configuration in injector")

var ErrInjectHTTPClientFailed = errors.New("inject http client failed")

type HTTPClientStarter struct {
}

func NewHTTPClientStarter() *HTTPClientStarter {
	return &HTTPClientStarter{}
}

func (receiver *HTTPClientStarter) Inject() string {
	return bytesutils.EmptyString
}

func (receiver *HTTPClientStarter) BeforeInjected(injector *inject.Graph) error {
	var err error
	configuration, ok := injectutils.FindInjectableByType[*configurations.HTTPClientConfiguration](new(configurations.HTTPClientConfiguration), injector)
	if !ok {
		return ErrMissHTTPClientConfigurationInInjector
	}
	client := resty.New()
	if configuration.EnableTrace {
		client.EnableTrace()
	} else {
		client.DisableTrace()
	}
	client.SetTimeout(configuration.DefaultTimeout.Duration)
	client.SetDebug(configuration.EnableDebug)

	json := jsoniter.ConfigCompatibleWithStandardLibrary
	client.JSONMarshal = json.Marshal
	client.JSONUnmarshal = json.Unmarshal

	if err = injector.Provide(&inject.Object{
		Value: client,
		Name:  "HTTPClient",
	}); err != nil {
		return fmt.Errorf("%w: %v", ErrInjectHTTPClientFailed, err)
	}
	return nil
}
